<template>
    <div class="container" align="center">
        <el-form ref="form" v-model="form" label-width="8em" style="width: 80%">
            <el-form-item label="配置浏览器">
				<el-row>
					<el-col :span="10">
						<el-tag>1、浏览器地址栏输入
							<span style="font-weight: bold; color: #e6a23c">chrome://flags/#unsafely-treat-insecure-origin-as-secure</span>
							回车
						</el-tag>
					</el-col>
					<el-col :offset="2" :span="10">
						<el-tag>2、文本框输入
							<span style="font-weight: bold; color: #e6a23c">{{target}}</span>
							后点击按钮启用并重启浏览器</el-tag>
					</el-col>
					<el-col :span="2">
						<el-button type="warning" size="mini" @click="showFlags = true" plain>详细</el-button>
					</el-col>
				</el-row>
				
            </el-form-item>

            <el-form-item label="配置文件">
                <input type="file" ref="file" @change="getFile" hidden>
                <el-input v-model="jsonPath"
                          placeholder="点击左侧图标选择 JSON 格式配置文件"
                          style="margin-bottom: 1em" disabled>
                    <template #prepend>
						<i class="el-icon-lx-file"></i>
                        <el-button @click="selectFile" style="color: #20a0ff">
							<DucumentAdd></DucumentAdd>
                        </el-button>
                    </template>
                </el-input>
            </el-form-item>

            <el-divider style="margin-bottom: 2em"><a style="color: #20a0ff">以下为配置信息预览</a></el-divider>

            <el-form-item label="服务器">
                <el-row>
                    <el-col v-for="(bit, index) in form.server.api.ip" :span="3">
                        <el-input v-model="form.server.api.ip[index]" :max="255" :min="0" disabled>
                            <template v-if="index!==3" #suffix>
                                <strong>.</strong>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :offset="2" :span="4">
                        <el-input v-model="form.server.api.port" disabled>
                            <template #prefix>
                                <strong>:</strong>
                            </template>
                        </el-input>
                    </el-col>
                    <p style="margin-left: 1em; color: #999999">（服务1）</p>
                </el-row>
                <el-row>
                    <el-col v-for="(bit, index) in form.server.call.ip" :span="3">
                        <el-input v-model="form.server.call.ip[index]" :max="255" :min="0" disabled>
                            <template v-if="index!==3" #suffix>
                                <strong>.</strong>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :offset="2" :span="4">
                        <el-input v-model="form.server.call.port" disabled>
                            <template #prefix>
                                <strong>:</strong>
                            </template>
                        </el-input>
                    </el-col>
                    <p style="margin-left: 1em; color: #999999">（服务2）</p>
                </el-row>
            </el-form-item>
            <el-form-item label="本站编号">
                <el-input v-model="form.sno" disabled></el-input>
            </el-form-item>
            <el-form-item label="本机 UUID">
                <el-input v-model="form.uuid" disabled></el-input>
            </el-form-item>
            <el-form-item label="本机 IP">
                <el-row>
                    <el-col v-for="(bit, index) in form.ip" :span="3">
                        <el-input v-model="form.ip[index]" :max="255" :min="0" disabled>
                            <template v-if="index!==3" #suffix>
                                <strong>.</strong>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :offset="3" :span="4">
                        <el-button type="text" @click="getIp">点击获取UUID和IP</el-button>
                    </el-col>
                </el-row>
            </el-form-item>

            <el-button type="primary" @click="submit" plain>{{ path.endsWith('setting') ? '更新' : '提交' }}</el-button>
            <el-button type="danger" v-if="path.endsWith('setting')" @click="reset" plain>重置</el-button>

        </el-form>
		
		<el-dialog v-model="showFlags" title="浏览器具体配置流程" center>
			<img src="../assets/img/flags.jpg">
		</el-dialog>
    </div>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import {reactive, ref} from "vue";
import {getDateTime} from "../utils/time";
import {getFingerprint} from "../utils/device";
import {addDevice, getIp, removeDevice} from "../api/setting";
import {SERVER, STATION} from "../api/common";

export default {
    name: "Setting",
    inject: ['reload'],
    data() {
        const path = this.$router.currentRoute.value.path;
        const form = reactive({
            server: {
                'api': {
                    'ip': SERVER.api.ip.split('.'),
                    'port': SERVER.api.port
                },
                'call': {
                    'ip': SERVER.call.ip.split('.'),
                    'port': SERVER.call.port
                }
            },
            sno: STATION.sno,
            uuid: STATION.uuid,
            ip: STATION.ip.split('.'),
        });
        const jsonPath = ref();
		let target = window.location.href.split('/');    //根路径
		target = target[0] + '//' + target[2];
		
		const showFlags = false
		
        return {
            path,
            form,
            jsonPath,
			target,
			showFlags
        }
    },
    methods: {

        getFile() {
            const file = this.$refs.file.files[0];
            if (file === null) return;
            //文件类型
            if (file.type !== 'application/json') {
                ElMessage.error('所选配置文件非JSON格式！');
                return;
            }
            //文件名及修改时间
            const lastModified = getDateTime(file.lastModified);
            this.jsonPath = '文件名称：' + file.name + '\t\t上次修改：' + lastModified;
            //读文件数据
            const reader = new FileReader();
            reader.readAsText(file);
            reader.onload = (e) => {
                let data = JSON.parse(e.target.result);
                this.form.server.api.ip = data.server.api.ip.split('.');
                this.form.server.api.port = data.server.api.port;
                this.form.server.call.ip = data.server.call.ip.split('.');
                this.form.server.call.port = data.server.call.port;
                this.form.sno = data.sno;
                //this.form.uuid = data.uuid;
                //this.form.ip = data.ip.split('.');

                //提前设置服务器信息
                const api_server = {
                    host: 'http://' + this.form.server.api.ip.join('.') + ':' + this.form.server.api.port,
                    ip: this.form.server.api.ip.join('.'),
                    port: this.form.server.api.port
                };
                const call_server = {
                    host: 'http://' + this.form.server.call.ip.join('.') + ':' + this.form.server.call.port,
                    ip: this.form.server.call.ip.join('.'),
                    port: this.form.server.call.port
                };
                localStorage.setItem('api_server', JSON.stringify(api_server));
                localStorage.setItem('call_server', JSON.stringify(call_server));
                localStorage.setItem('sno', this.form.sno);
            };

            //强制刷新，避免使用脏服务器地址
            location.reload();
        },
        selectFile() {
            const file = this.$refs.file;
            file.click();
        },

        getIp() {
            this.form.uuid = getFingerprint();
            localStorage.setItem('uuid', this.form.uuid);
            getIp()
              .then((res) => {
                  if (res.code === 0) {
                      this.form.ip = res.data.split('.');
                      localStorage.setItem('ip', this.form.ip.join('.'));
                  }
              })
              .catch(() => {
                  ElMessage.error('服务器未启动或其它错误！');
              })

        },
        submit() {
            // const api_server = {
            // 	host: 'http://' + this.form.server.api.ip.join('.') + ':' + this.form.server.api.port,
            // 	ip: this.form.server.api.ip.join('.'),
            // 	port: this.form.server.api.port
            // };
            // const call_server = {
            // 	host: 'http://' + this.form.server.call.ip.join('.') + ':' + this.form.server.call.port,
            // 	ip: this.form.server.call.ip.join('.'),
            // 	port: this.form.server.call.port
            // };
            // localStorage.setItem('api_server', JSON.stringify(api_server));
            // localStorage.setItem('call_server', JSON.stringify(call_server));
            // localStorage.setItem('sno', this.form.sno);
            // localStorage.setItem('uuid', this.form.uuid);
            // localStorage.setItem('ip', this.form.ip.join('.'));

            //刷新页面，否则会使用脏服务器地址
            //location.reload();
            if (!localStorage.getItem('sno') || !localStorage.getItem('ip')) {
                ElMessage.error('请在全部配置完成后进行提交！');
                return;
            }

            //提交给服务器
            addDevice(this.form)
              .then((res) => {
                  if (res.code === 0) {
                      localStorage.setItem('deviceId', res.data.deviceId);
                      localStorage.setItem('id', res.data.stationId);
                      ElMessage.success('更新成功！');
                      location.reload();
                  }
              })
              .catch(() => {
                  ElMessage.error('服务器未启动或其他错误！');
              })
        },
        reset() {
            ElMessageBox.confirm('确认要重置配置信息吗？', '提示', {
                type: 'warning'
            })
              .then(async () => {
                  //清除配置并刷新
                  await removeDevice(localStorage.getItem('id'))
                    .then((res) => {
                        if (res.code === 0) {
                            ElMessage.success('重置成功！');
                            localStorage.clear();
                            this.$router.push('/init');
                            setTimeout(() => {
                                location.reload();
                            }, 1000);
                        } else {
                            ElMessage.error('重置失败！');
                        }
                    });

              })
              .catch(() => {
              })
        }
    },
}
</script>

<style scoped>

</style>